﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.IO;
using System.Windows.Forms;
using System.Reflection;
using SolutionSorter.Core;

namespace SolutionSorter
{
    public class FileResolver : IFileResolver
    {
        public FileResolver(IConfiguration config)
        {
            _args = config.ProgramArgs;
        }

        public string GetFilePath()
        {
            if (_filePath == null)
            {
                // TODO: consider implementing a ChainOfResponsiblity pattern here
                if (TryGetFilePath()) return _filePath;
                else if (TryScanFilePath()) return _filePath;
                else if (TryPromptFilePath()) return _filePath;
                return "";
            }
            return _filePath;
        }

        private bool TryGetFilePath()
        {
            if (_args == null || _args.Length == 0 || _args[0] == null || _args[0] == "")
            {
                _filePath = "";
                return false;
            }
            else
            {
                _filePath = _args[0];
                return true;
            }
        }

        private bool TryScanFilePath()
        {
            string path = GetCurrentPath();
            string[] matches = Directory.GetFiles(path, "*.sln");
            if (matches.Length == 0 || matches.Length > 1)
            {
                _filePath = "";
                return false;
            }
            else
            {
                _filePath = matches[0];
                return true;
            }
        }

        private bool TryPromptFilePath()
        {
            OpenFileDialog dialog = new OpenFileDialog();
            dialog.Title = "Choose a Visual Studio Solution file to sort";
            dialog.InitialDirectory = GetCurrentPath();
            dialog.Filter = "Solution Files (*.sln)|*.sln";
            if (dialog.ShowDialog() == DialogResult.OK)
            {
                _filePath = dialog.FileName;
                return true;
            }
            else
            {
                _filePath = "";
                return false;
            }
        }

        private static string GetCurrentPath()
        {
            return Path.GetDirectoryName(Assembly.GetExecutingAssembly().Location);
        }

        private readonly string[] _args;
        private string _filePath;
    }
}

